package com.gyj.server.core;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 自我保护机制
 * @author Gao
 * @date 2021/6/26
 */
public class SelfProtectionPolicy {

    private static final Logger logger = LogManager.getLogger(SelfProtectionPolicy.class);

    /**
     * 单例模式
     */
    private static SelfProtectionPolicy instance = new SelfProtectionPolicy();

    private SelfProtectionPolicy() {

    }

    /**
     * 自我保护机制单例模式
     * @return
     */
    public static SelfProtectionPolicy getInstance() {
        return instance;
    }

    /**
     * 期望的一个心跳次数，如10个服务实例，1分钟内心跳次数10*2=20
     */
    private long expectedHeartbeatRate = 0L;

    /**
     * 期望心跳次数的阈值，如10个服务实例，10*2*0.85=17次
     */
    private long expectedHeartbeatThreshold = 0L;

    /**
     * 判断自我保护模式是否开启
     * @return
     */
    public Boolean isEnable() {
        HeartBeatCounter heartBeatRate = HeartBeatCounter.getInstance();
        long count = heartBeatRate.getCount();
        if (count < expectedHeartbeatThreshold) {
            logger.info("自我保护阈值开启，最新一分钟心跳次数:{}, 期望阈值:{}", count, expectedHeartbeatThreshold);
            return true;
        }
        return false;
    }


    public long getExpectedHeartbeatThreshold() {
        return expectedHeartbeatThreshold;
    }

    public void setExpectedHeartbeatThreshold(long expectedHeartbeatThreshold) {
        this.expectedHeartbeatThreshold = expectedHeartbeatThreshold;
    }

    public long getExpectedHeartbeatRate() {
        return expectedHeartbeatRate;
    }

    public void setExpectedHeartbeatRate(long expectedHeartbeatRate) {
        this.expectedHeartbeatRate = expectedHeartbeatRate;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
    }

}
